from flask import Flask, jsonify
from flask_cors import CORS
import logging
import signal
import sys
from config import config
from database import db
from mqtt_client import mqtt_client
from api.devices import devices_bp
from api.config import config_bp
from api.wards import wards_bp
from api.statistics import statistics_bp

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('iot_platform.log', encoding='utf-8'),
        logging.StreamHandler()
    ]
)

logger = logging.getLogger(__name__)


def create_app():
    """创建Flask应用"""
    app = Flask(__name__)
    app.config['SECRET_KEY'] = config.SECRET_KEY
    
    # 启用CORS
    CORS(app, resources={
        r"/api/*": {
            "origins": "*",
            "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
            "allow_headers": ["Content-Type", "Authorization"]
        }
    })
    
    # 注册蓝图
    app.register_blueprint(devices_bp)
    app.register_blueprint(config_bp)
    app.register_blueprint(wards_bp)
    app.register_blueprint(statistics_bp)
    
    # 健康检查接口
    @app.route('/api/health', methods=['GET'])
    def health_check():
        return jsonify({
            'code': 200,
            'message': '服务运行正常',
            'data': {
                'mqtt_connected': mqtt_client.connected,
                'version': '1.0.0'
            }
        })
    
    # 根路径
    @app.route('/', methods=['GET'])
    def index():
        return jsonify({
            'code': 200,
            'message': '物联网设备管理平台API',
            'version': '1.0.0'
        })
    
    # 错误处理
    @app.errorhandler(404)
    def not_found(error):
        return jsonify({
            'code': 404,
            'message': '接口不存在'
        }), 404
    
    @app.errorhandler(500)
    def internal_error(error):
        return jsonify({
            'code': 500,
            'message': '服务器内部错误'
        }), 500
    
    return app


def init_services():
    """初始化服务"""
    logger.info("正在初始化服务...")
    
    # 连接MongoDB
    if not db.connect_mongodb():
        logger.error("MongoDB连接失败，服务启动终止")
        sys.exit(1)
    
    # 连接MQTT
    if not mqtt_client.connect():
        logger.error("MQTT连接失败，服务启动终止")
        sys.exit(1)
    
    logger.info("所有服务初始化完成")


def cleanup_services(signum=None, frame=None):
    """清理服务"""
    logger.info("正在关闭服务...")
    
    mqtt_client.disconnect()
    db.close()
    
    logger.info("服务已关闭")
    sys.exit(0)


# 注册信号处理
signal.signal(signal.SIGINT, cleanup_services)
signal.signal(signal.SIGTERM, cleanup_services)


if __name__ == '__main__':
    # 初始化服务
    init_services()
    
    # 创建Flask应用
    app = create_app()
    
    # 启动服务器
    logger.info(f"正在启动服务器: {config.HOST}:{config.PORT}")
    try:
        app.run(
            host=config.HOST,
            port=config.PORT,
            debug=config.DEBUG,
            threaded=True
        )
    except Exception as e:
        logger.error(f"服务器启动失败: {e}")
        cleanup_services()

